<?php

/**
 * Copyright 2010 - 2013, Cake Development Corporation (http://cakedc.com)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright 2010 - 2013, Cake Development Corporation (http://cakedc.com)
 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

class UsuariosController extends UsuariosAppController {

    /**
     * Controller name
     *
     * @var string
     */
    public $name = 'Usuarios';
    public $uses = array('Usuarios.Usuario');

    /**
     * Constructor
     *
     * @param CakeRequest $request Request object for this controller. Can be null for testing,
     *  but expect that features that use the request parameters will not work.
     * @param CakeResponse $response Response object for this controller.
     */
    public function __construct($request, $response) {
        parent::__construct($request, $response);
    }

    /**
     * Common login action
     *
     * @return void
     */
    public function login() {
        $this->theme = 'default';
        $this->layout = 'login';
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $this->Usuario->id = $this->Auth->usuario('id');
                $this->Usuario->saveField('last_login', date('Y-m-d H:i:s'));
                $this->redirect(array('action' => 'index', 'admin' => TRUE));
            } else {
                $this->Session->setFlash(__d('usuarios', 'Invalid e-mail / password combination.  Please try again'), 'alert', array(
                    'plugin' => 'BoostCake',
                    'class' => 'alert-danger'
                ));
            }
        }
    }

    /**
     * Common logout action
     *
     * @return void
     */
    public function logout() {
        $user = $this->Auth->user();
        $this->Session->destroy();
        if (isset($_COOKIE[$this->Cookie->name])) {
            $this->Cookie->destroy();
        }
        $this->RememberMe->destroyCookie();
        $this->Session->setFlash(sprintf(__d('usuarios', '%s you have successfully logged out'), $usuario[$this->Usuario->displayField]), 'alert', array(
            'plugin' => 'BoostCake',
            'class' => 'alert-success'
        ));
        $this->redirect($this->Auth->logout());
    }

    /**
     * index method
     *
     * @return void
     */
    public function admin_index() {
        $this->Paginator->settings = array(
            'limit' => 10
        );
        $this->set('usuarios', $this->Paginator->paginate('Usuario'));
        $this->set('title', 'Usuário - Consultar');
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function admin_view($id = null) {
        if (!$this->Usuario->exists($id)) {
            throw new NotFoundException(__('Invalid usuario'));
        }
        $options = array('conditions' => array('Usuario.' . $this->Usuario->primaryKey => $id));
        $this->set('usuario', $this->Usuario->find('first', $options));
        $this->set('title', 'Usuário - Detalhes');
    }

    /**
     * add method
     *
     * @return void
     */
    public function add() {
        if ($this->request->is('post')) {
            $this->Usuario->create();
            if ($this->__save($this->request->data)) {
                $this->Session->setFlash(__('The usuario has been saved.'), 'alert', array(
                    'plugin' => 'BoostCake',
                    'class' => 'alert-danger'
                ));
                return $this->redirect('/login');
            } else {
                $this->Session->setFlash(__('The usuario could not be saved. Please, try again.'), 'alert', array(
                    'plugin' => 'BoostCake',
                    'class' => 'alert-danger'
                ));
            }
        }
        $this->set('title', 'Usuário - Cadastrar');
    }

    /**
     * add method
     *
     * @return void
     */
    public function admin_add() {
        if ($this->request->is('post')) {
            if ($this->__save($this->request->data)) {
                $this->Session->setFlash(__('The usuario has been saved.'), 'alert', array(
                    'plugin' => 'BoostCake',
                    'class' => 'alert-success'
                ));
                return $this->redirect(array('action' => 'edit', $this->Usuario->id));
            } else {
                $this->Session->setFlash(__('The usuario could not be saved. Please, try again.'), 'alert', array(
                    'plugin' => 'BoostCake',
                    'class' => 'alert-danger'
                ));
            }
        }
        $this->set('title', 'Usuário - Cadastrar');
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function admin_edit($id = null) {
        if (!$this->Usuario->exists($id)) {
            throw new NotFoundException(__('Invalid usuario'));
        }
        if ($this->request->is(array('post', 'put'))) {
            if ($this->__save($this->request->data)) {
                $this->Session->setFlash(__('The usuario has been saved.'), 'alert', array(
                    'plugin' => 'BoostCake',
                    'class' => 'alert-success'
                ));
                return $this->redirect($this->referer());
            } else {
                $this->Session->setFlash(__('The usuario could not be saved. Please, try again.'), 'alert', array(
                    'plugin' => 'BoostCake',
                    'class' => 'alert-danger'
                ));
            }
        } else {
            $options = array('conditions' => array('Usuario.' . $this->Usuario->primaryKey => $id));
            $this->request->data = $this->Usuario->find('first', $options);
        }
        $this->set('title', 'Usuário - Editar');
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function admin_delete($id = null) {
        $this->Usuario->id = $id;
        if (!$this->Usuario->exists()) {
            throw new NotFoundException(__('Invalid usuario'));
        }
        $this->request->allowMethod('post', 'delete');
        if ($this->Usuario->delete()) {
            $this->Session->setFlash(__('The usuario has been deleted.'), 'alert', array(
                'plugin' => 'BoostCake',
                'class' => 'alert-success'
            ));
        } else {
            $this->Session->setFlash(__('The usuario could not be deleted. Please, try again.'), 'alert', array(
                'plugin' => 'BoostCake',
                'class' => 'alert-danger'
            ));
        }
        return $this->redirect($this->referer());
    }

    public function admin_permissao($id) {
        $this->loadModel('Usuarios.Menu');
        $this->loadModel('Usuarios.UsuariosMenu');
        $menu = $this->Menu->find('all', array('conditions' => array('Menu.status' => 1)));
        if ($this->request->is('post')) {
            $this->UsuariosMenu->deleteAll(array('UsuariosMenu.usuario_id' => $id), false);
            foreach ($this->request->data['Menu'] as $key => $value) {
                $this->UsuariosMenu->save(array('UsuariosMenu' => array('usuario_id' => $id, 'menu_id' => $value['id'])));
                $this->UsuariosMenu->clear();
            }
        }
        $usuariosMenu = $this->UsuariosMenu->findById($id);
        $this->set(compact('menu', 'usuariosMenu', 'id'));
        $this->set('title', 'Usuário - Permissão');
    }

    private function __save($data = null, $validate = true, $fieldList = array()) {
        if (isset($data['Usuario']['password']) AND ! empty($data['Usuario']['password'])) {
            $data['Usuario']['password'] = AuthComponent::password($data['Usuario']['password']);
        }
        return $this->Usuario->save($data, $validate, $fieldList);
    }

}
